package com.sinux.generality.provider.demo.controller.base;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sinux.generality.basesupport.utils.query.OConvertUtils;
import com.sinux.generality.provider.demo.constants.Sets;
import com.sinux.generality.provider.demo.tool.SpringContextUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.lang.reflect.Method;
import java.util.List;

@Controller
public class BaseController {
    @Value("${common}")
    private String common;
    @ApiOperation("保存数据")
    @PostMapping("/save")
    public String save(@RequestBody JSONObject jsonObject){
//        String entityKey = jsonObject.getString("entityKey");
        String controllerName = this.getClass().getSimpleName();
        String entityKey = controllerName.replaceAll("Controller", "");
        try {
            ServiceImpl service = (ServiceImpl) SpringContextUtil.getBean(Class.forName(common+"service."+entityKey+"Service"));
            Class entityType = Class.forName(common+"entity." + entityKey);
            Object obj = jsonObject.getObject("body", entityType);
            service.getBaseMapper().insert(obj);
//            return ok();
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @ApiOperation("修改数据")
    @PostMapping("/update")
    public String update(@RequestBody JSONObject jsonObject){
//        String entityKey = jsonObject.getString("entityKey");
        String controllerName = this.getClass().getSimpleName();
        String entityKey = controllerName.replaceAll("Controller", "");
        try {
            ServiceImpl service = (ServiceImpl) SpringContextUtil.getBean(Class.forName(common+"service."+entityKey+"Service"));
            Class entityType = Class.forName(common+"entity." + entityKey);
            Object obj = jsonObject.getObject("body", entityType);
            service.getBaseMapper().updateById(obj);
            return ok();
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @ApiOperation("统一删除数据")
    @PostMapping("/delCommon")
    public String commonDel(@RequestBody JSONObject jsonObject){
        String controllerName = this.getClass().getSimpleName();
        String entityKey = controllerName.replaceAll("Controller", "");
        try {
            ServiceImpl service = (ServiceImpl) SpringContextUtil.getBean(Class.forName(common+"service."+entityKey+"Service"));
//            Class entityType = Class.forName("com.cetc10.hjj.simulation.data.entity." + entityKey);
            String id = jsonObject.getString("body");
            service.getBaseMapper().deleteById(id);
            return ok();
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @ApiOperation("统一检索数据集合")
    @PostMapping("/listCommon")
    public String commonList(@RequestBody JSONObject jsonObject){
        String controllerName = this.getClass().getSimpleName();
        String entityKey = controllerName.replaceAll("Controller", "");
        try {
            ServiceImpl service = (ServiceImpl) SpringContextUtil.getBean(Class.forName(common+"service."+entityKey+"Service"));
//            Class entityType = Class.forName("com.cetc10.hjj.simulation.data.entity." + entityKey);
            JSONObject param = jsonObject.getJSONObject("body");
            QueryWrapper qw = new QueryWrapper();
            for(String key: param.keySet()){
                Method m = Sets.queryWrapperMap.get(key);
                JSONArray paramArray = param.getJSONArray(key);
                for(int i=0;i<paramArray.size();i++) {
                    JSONObject paramJson = paramArray.getJSONObject(i);
                    m.invoke(qw, OConvertUtils.camelToUnderline(paramJson.getString("key")), paramJson.getString("val"));
                }
            }
            List list =  service.getBaseMapper().selectList(qw);
            return ok(list);
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @ApiOperation("统一检索数据分页")
    @PostMapping("/pageCommon")
    public String commonPage(@RequestBody JSONObject jsonObject){
        String controllerName = this.getClass().getSimpleName();
        String entityKey = controllerName.replaceAll("Controller", "");
        try {
            ServiceImpl service = (ServiceImpl) SpringContextUtil.getBean(Class.forName(common+"service."+entityKey+"Service"));
//            Class entityType = Class.forName("com.cetc10.hjj.simulation.data.entity." + entityKey);
            int size = jsonObject.getInteger("size");
            int current = jsonObject.getInteger("current");
            JSONObject param = jsonObject.getJSONObject("body");
            Page page = new Page<>(current, size);
            QueryWrapper qw = new QueryWrapper();
            for(String key: param.keySet()){
                Method m = Sets.queryWrapperMap.get(key);
                JSONArray paramArray = param.getJSONArray(key);
                for(int i=0;i<paramArray.size();i++) {
                    JSONObject paramJson = paramArray.getJSONObject(i);
                    m.invoke(qw, OConvertUtils.camelToUnderline(paramJson.getString("key")), paramJson.getString("val"));
                }
            }
            IPage resPage =  service.getBaseMapper().selectPage(page, qw);
            resPage.setTotal(resPage.getRecords().size());
            return ok(resPage);
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }


    private static final String RESULT_STRING_BEGIN = "{\"code\":";
    private static final String RESULT_STRING_MID = ",\"data\":";
    private static final String RESULT_STRING_END = ",\"message\":\"\"}";
    private static final String LINK_UP = "\"";

    protected String ok(){
        return ok("", false);
    }

    protected String ok(Object obj){
        return ok(JSON.toJSONString(obj), true);
    }

    protected String ok(String json){
        return result("200", json, false);
    }

    private String ok(String json, boolean isObj){
        return result("200", json, isObj);
    }
    protected String error(){return error("", false);}

    protected String error(Object obj){
        return error(JSON.toJSONString(obj), true);
    }

    protected String error(String json){
        return result("100", json, false);
    }

    private String error(String json, boolean isObj){
        return result("100", json, isObj);
    }

    private String result(String code, String json, boolean isObj){
        if(isObj){
            return RESULT_STRING_BEGIN+code+RESULT_STRING_MID+json+RESULT_STRING_END;
        }else{
            return RESULT_STRING_BEGIN+code+RESULT_STRING_MID+LINK_UP+json+LINK_UP+RESULT_STRING_END;
        }
    }
}
